package com.xiaoshuai.plat.util.weixin;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
import java.text.ParseException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.net.www.protocol.https.Handler;

import com.xiaoshuai.plat.common.weixin.WXConstants;
import com.xiaoshuai.plat.model.WXUserInfo;
import com.xiaoshuai.plat.vo.AccessToken;
import com.xiaoshuai.plat.vo.Menu;
import com.xiaoshuai.plat.vo.OAuthInfo;
import com.xiaoshuai.plat.vo.UserInfo;

/**
 * 公众平台通用接口工具类
 */
public class WeixinUtil {
	private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);

	public String js_api_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	public static final String jsticket = "bxLdikRXVbTPdHSM05e5u8W5L2c5jvDSSiPMQiA3d-wUG1flyddlkZjqWjdplCpWDAKAeXToWhszAat-Yk3DfA";
	public static String testUrl = "https://api.weixin.qq.com/card/qrcode/create?access_token=TOKEN";

	public static String test = "{\"card\":{\"card_type\":\"DISCOUNT\",\"discount\":{\"base_info\":{\"title\":\"132元双人火锅套餐\",\"date_info\":{\"end_timestamp\":1472724261,\"begin_timestamp\":1397577600,\"type\":\"DATE_TYPE_FIX_TIME_RANGE\"},\"color\":\"Color010\",\"description\":\"不可用叠加使用\",\"sku\":{\"quantity\":10000},\"notice\":\"请出示你的卡券给服务人员\",\"logo_url\":\"http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZJkmG8xXhiaHqkKSVMMWeN3hLut7X7hicFNjakmxibMLGWpXrEXB33367o7zHN0CwngnQY7zb7g/0\",\"brand_name\":\"测试卡券\",\"code_type\":\"CODE_TYPE_TEXT\"},\"discount\":30}}}";
	public static final String create_ticket = "https://api.weixin.qq.com/card/create?access_token=ACCESS_TOKEN";
	public static final String APITICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";
	public static final String DeviceUrl = "https://api.weixin.qq.com/device/authorize_device?access_token=ACCESS_TOKEN";
	public static final String DeviceUrl_new = "https://api.weixin.qq.com/device/getqrcode?access_token=ACCESS_TOKEN&product_id=PRODUCT_ID";
	public static final String bind_url = "https://api.weixin.qq.com/device/bind?access_token=ACCESS_TOKEN";
	public static final String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	public static String batchget_material_url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";

	public static String get_material_url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=ACCESS_TOKEN";

	public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

	public static String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	public static String userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	public static String userinfo_url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";

	public static void main(String[] args) throws ParseException {
		if (WXConstants.ACCESS_TOKEN == null) {
			WXConstants.ACCESS_TOKEN = getAccessToken("wx2d39c6c31ed5f144",
					"a593fa37e25ddc96027462ec2c3fa2ce");
		}
		System.out.println(WXConstants.ACCESS_TOKEN.getToken());
	}

	public static Object getQRcode(String appid, String appsecret) {
		if (WXConstants.ACCESS_TOKEN == null) {
			WXConstants.ACCESS_TOKEN = getAccessToken(appid, appsecret);
		}
		return null;
	}

	// public static ReturnCard putTicket(String appid, String appsecret)
	// {
	// if (WXConstants.ACCESS_TOKEN == null) {
	// WXConstants.ACCESS_TOKEN = getAccessToken(appid, appsecret);
	// }
	// ReturnCard card = new ReturnCard();
	// String requestUrl =
	// "https://api.weixin.qq.com/card/create?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN",
	// WXConstants.ACCESS_TOKEN.getToken());
	// JSONObject jsonObject = httpRequest(requestUrl, "POST", test);
	// if (jsonObject.get("errcode").equals(Integer.valueOf(0))) {
	// card.setCard_id(jsonObject.getString("card_id"));
	// } else {
	// System.out.println("错误了 错误代码 errcode :" + jsonObject.getInt("errcode") +
	// "\n 错误信息 errmsg： " + jsonObject.getString("errmsg"));
	// log.error("错误了 错误代码 errcode :" + jsonObject.getString("errcode") +
	// "\n 错误信息 errmsg： " + jsonObject.getString("errmsg"));
	// }
	// return null;
	// }

	// public static ApiTicket getApiTicket(String appid, String appsecret)
	// {
	// AccessToken token = new AccessToken();
	// token = getAccessToken(appid, appsecret);
	// ApiTicket apiTicket = new ApiTicket();
	// String requestUrl =
	// "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card".replace("ACCESS_TOKEN",
	// token.getToken());
	// JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
	// if (jsonObject.get("errcode").equals(Integer.valueOf(0))) {
	// apiTicket.setTicket(jsonObject.getString("ticket"));
	// apiTicket.setExpires_in(jsonObject.getString("expires_in"));
	// } else {
	// System.out.println("错误了 错误代码 errcode :" + jsonObject.getInt("errcode") +
	// "\n 错误信息 errmsg： " + jsonObject.getString("errmsg"));
	// log.error("错误了 错误代码 errcode :" + jsonObject.getString("errcode") +
	// "\n 错误信息 errmsg： " + jsonObject.getString("errmsg"));
	// }
	// return apiTicket;
	// }
	// public JsapiTicket getJsapiTicket(String appid, String appsecret) {
	// AccessToken token = new AccessToken();
	// token = getAccessToken(appid, appsecret);
	// JsapiTicket ticket = new JsapiTicket();
	// String requestUrl = this.js_api_ticket_url.replace("ACCESS_TOKEN",
	// token.getToken());
	// JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
	// if (jsonObject.getString("errcode").equals("0")) {
	// ticket.setTicket(jsonObject.getString("ticket"));
	// ticket.setExpiresIn(jsonObject.getString("expires_in"));
	// } else {
	// System.out.println("错误信息" + jsonObject.getString("errcode") + "\n " +
	// jsonObject.getString("errmsg"));
	// log.error("error");
	// }
	// return ticket;
	// }

	public String getDevice(String appid, String appsecret, String devices) {
		AccessToken token = new AccessToken();
		token = getAccessToken(appid, appsecret);
		String requestUrl = "https://api.weixin.qq.com/device/authorize_device?access_token=ACCESS_TOKEN"
				.replace("ACCESS_TOKEN", token.getToken());
		JSONObject jsonObject = httpRequest(requestUrl, "POST", devices);
		if (!jsonObject.getString("errcode").equals("0")) {
			System.out.println("错误信息" + jsonObject.getString("errcode") + "\n "
					+ jsonObject.getString("errmsg"));
			log.error("error");
		}
		return jsonObject.toString();
	}

	public String getDeviceNew(String appid, String appsecret, String productid) {
		AccessToken token = new AccessToken();
		token = getAccessToken(appid, appsecret);
		String requestUrl = "https://api.weixin.qq.com/device/getqrcode?access_token=ACCESS_TOKEN&product_id=PRODUCT_ID"
				.replace("ACCESS_TOKEN", token.getToken()).replace(
						"PRODUCT_ID", productid);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		if (jsonObject.getString("deviceid") != null) {
			System.out.println(jsonObject.toString());
		} else {
			System.out.println("错误信息" + jsonObject.getString("errcode") + "\n "
					+ jsonObject.getString("errmsg"));
			log.error("error");
		}
		return jsonObject.toString();
	}

	public String bindCard(String appid, String appsecret, String info) {
		AccessToken token = new AccessToken();
		token = getAccessToken(appid, appsecret);
		String requestUrl = "https://api.weixin.qq.com/device/bind?access_token=ACCESS_TOKEN"
				.replace("ACCESS_TOKEN", token.getToken());
		JSONObject jsonObject = httpRequest(requestUrl, "POST", info);
		if (jsonObject.getString("deviceid") != null) {
			System.out.println(jsonObject.toString());
		} else {
			System.out.println("错误信息" + jsonObject.getString("errcode") + "\n "
					+ jsonObject.getString("errmsg"));
			log.error("error");
		}
		return jsonObject.toString();
	}

	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		System.out.println("==============进入httpRequest方法===============");

		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new SecureRandom());

			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(null, requestUrl, new Handler());
			System.out
					.println("==============发送的url" + url + "===============");
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			System.out.println("============== url.openConnection()"
					+ httpUrlConn + "===============");

			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			}

			if (outputStr != null) {
				OutputStream outputStream = httpUrlConn.getOutputStream();

				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			System.out.println("============== buffer.toString()"
					+ buffer.toString() + "===============");
			bufferedReader.close();
			inputStreamReader.close();

			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
			System.out.println("============== jsonObject" + jsonObject
					+ "===============");
		} catch (ConnectException ce) {
			System.out
					.println("============== Weixin server connection timed out."
							+ ce + "===============");
		} catch (Exception e) {
			System.out.println("==============https request error:{}" + e
					+ "===============");
		}

		System.out.println("==============httpRequest方法结束===============");
		return jsonObject;
	}

	public static boolean httpRequestNoResult(String requestUrl,
			String requestMethod, String outputStr) {
		boolean result = false;
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new SecureRandom());

			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod)) {
				httpUrlConn.connect();
			}

			if (outputStr != null) {
				OutputStream outputStream = httpUrlConn.getOutputStream();

				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			if (httpUrlConn.getResponseCode() == 200) {
				result = true;
			}

			httpUrlConn.disconnect();
		} catch (ConnectException localConnectException) {
		} catch (Exception localException) {
		}
		return result;
	}

	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
				.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);

		if (jsonObject != null) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
				WXConstants.setACCESS_TOKEN(accessToken);
			} catch (JSONException e) {
				accessToken = null;
			}

		}

		return accessToken;
	}

	public static void batchgetMaterial(String appid, String appsecret,
			String param) {
		AccessToken accessToken = getAccessToken(appid, appsecret);
		String requestUrl = batchget_material_url.replace("ACCESS_TOKEN",
				accessToken.getToken());
		JSONObject jsonObject = httpRequest(requestUrl, "POST", param);
		if (jsonObject != null)
			System.out.println(jsonObject);
		else
			System.out.println(jsonObject.get("errcode"));
	}

	public static void getMaterial(String appid, String appsecret) {
		AccessToken accessToken = getAccessToken(appid, appsecret);
		String requestUrl = get_material_url.replace("ACCESS_TOKEN",
				accessToken.getToken());
		JSONObject jsonObject = httpRequest(requestUrl, "POST", null);
		if (jsonObject == null) {
			System.out.println(jsonObject.get("errcode"));
		}
	}

	public static int createMenu(Menu menu, String accessToken) {
		int result = 0;

		String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);

		String jsonMenu = JSONObject.fromObject(menu).toString();

		JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);

		if ((jsonObject != null) && (jsonObject.getInt("errcode") != 0)) {
			result = jsonObject.getInt("errcode");
		}

		return result;
	}

	public static OAuthInfo getOAuthOpenId(String appid, String secret,
			String code) {
		OAuthInfo oAuthInfo = null;
		String requestUrl = o_auth_openid_url.replace("APPID", appid)
				.replace("SECRET", secret).replace("CODE", code);
		System.out.println("==============requestUrl:" + requestUrl
				+ "==============");

		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		System.out.println("==============jsonObject:" + jsonObject
				+ "==============");

		if (jsonObject != null) {
			try {
				oAuthInfo = new OAuthInfo();
				oAuthInfo.setAccessToken(jsonObject.getString("access_token"));
				oAuthInfo.setExpiresIn(jsonObject.getInt("expires_in"));
				oAuthInfo
						.setRefreshToken(jsonObject.getString("refresh_token"));
				oAuthInfo.setOpenId(jsonObject.getString("openid"));
				oAuthInfo.setScope(jsonObject.getString("scope"));
			} catch (JSONException e) {
				oAuthInfo = null;

				log.error("网页授权获取openId失败 errcode:{} errmsg:{}",
						Integer.valueOf(jsonObject.getInt("errcode")),
						jsonObject.getString("errmsg"));
			}
		}
		return oAuthInfo;
	}

	public static WXUserInfo getWXUserInfo(String access_token, String openid) {
		WXUserInfo wxuserInfo = null;
		String requestUrl = userinfo_url2.replace("ACCESS_TOKEN", access_token)
				.replace("OPENID", openid);
		System.out.println("==============requestUrl:" + requestUrl
				+ "==============");
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		System.out.println("==============jsonObject:" + jsonObject
				+ "==============");

		if (jsonObject != null) {
			try {
				wxuserInfo = new WXUserInfo();
				wxuserInfo.setSubscribe(jsonObject.getInt("subscribe"));
				wxuserInfo.setOpenid(jsonObject.getString("openid"));
				wxuserInfo.setNickname(jsonObject.getString("nickname"));
				wxuserInfo.setSex(jsonObject.getInt("sex"));
				wxuserInfo.setLanguage(jsonObject.getString("language"));
				wxuserInfo.setCity(jsonObject.getString("city"));
				wxuserInfo.setProvince(jsonObject.getString("province"));
				wxuserInfo.setCountry(jsonObject.getString("country"));
				wxuserInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
				wxuserInfo.setSubscribe_time(jsonObject
						.getString("subscribe_time"));
				wxuserInfo.setUnionid(jsonObject.getString("unionid"));
				wxuserInfo.setRemark(jsonObject.getString("remark"));
				wxuserInfo.setGroupid(jsonObject.getInt("groupid"));
				wxuserInfo.setTagid_list(jsonObject.getJSONArray("tagid_list"));
			} catch (Exception e) {
				e.printStackTrace();
				if (jsonObject.containsKey("errcode")) {
					log.error("网页授权获取openId失败 errcode:{} errmsg:{}",
							jsonObject.getString("errcode"),
							jsonObject.getString("errmsg"));
					return null;
				}
				log.info("取值错误=========" + e.getMessage());
				return null;
			}
		}

		return wxuserInfo;
	}

	public static UserInfo getUserInfo(String access_token, String openid) {
		UserInfo userInfo = null;
		String requestUrl = userinfo_url2.replace("ACCESS_TOKEN", access_token)
				.replace("OPENID", openid);
		System.out.println("==============requestUrl:" + requestUrl
				+ "==============");

		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		System.out.println("==============jsonObject:" + jsonObject
				+ "==============");

		if (jsonObject != null) {
			try {
				userInfo = new UserInfo();
				userInfo.setNickname(jsonObject.getString("nickname"));
				userInfo.setHeadimgurl(jsonObject.getString("headimgurl"));
				userInfo.setCity(jsonObject.getString("city"));
			} catch (JSONException e) {
				userInfo = null;

				log.error("网页授权获取openId失败 errcode:{} errmsg:{}",
						Integer.valueOf(jsonObject.getInt("errcode")),
						jsonObject.getString("errmsg"));
			}
		}
		return userInfo;
	}
}